﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Utility;
using DAL;
using System.Data.SqlClient;
using System.Data;
using BLL;

public partial class Admin_Department_EditYearDepartmentSlogans : System.Web.UI.Page
{
    string path = HttpContext.Current.Server.MapPath("~/") + @"Admin\Upload\";
    string SQL_queryIntroduction = "SELECT * FROM [DS_IntroductionImg] WHERE DepartmentId=@DepartmentId AND DateId=@DateId ORDER BY OrderValue";
    string SQL_queryManagementSlogans = "SELECT * FROM [DS_ManagementSlogans] WHERE DepartmentId=@DepartmentId AND DateId=@DateId ORDER BY OrderValue";
    string SQL_queryCoreevents = "SELECT * FROM [DS_CoreeventsImg] WHERE DepartmentId=@DepartmentId AND DateId=@DateId ORDER BY OrderValue";
    string SQL_queryManagementObject = "SELECT * FROM [DS_ManagementObject] WHERE DepartmentId=@DepartmentId AND DateId=@DateId ORDER BY OrderValue";

    string SQL_insertIntroduction = "INSERT INTO  [DS_IntroductionImg]([DepartmentId],ImgUrl,[IsDefault],[OrderValue],[DateId])VALUES(@DepartmentId,@ImgUrl,@IsDefault,@OrderValue,@DateId)";
    string SQL_insertManagementSlogans = "INSERT INTO  [DS_ManagementSlogans]([DepartmentId],ImgUrl,[IsDefault],[OrderValue],[DateId])VALUES(@DepartmentId,@ImgUrl,@IsDefault,@OrderValue,@DateId)";
    string SQL_insertCoreevents = "INSERT INTO  [DS_CoreeventsImg]([DepartmentId],ImgUrl,[IsDefault],[OrderValue],[DateId])VALUES(@DepartmentId,@ImgUrl,@IsDefault,@OrderValue,@DateId)";
    string SQL_insertManagementObject = "INSERT INTO  [DS_ManagementObject]([DepartmentId],ImgUrl,[IsDefault],[OrderValue],[DateId])VALUES(@DepartmentId,@ImgUrl,@IsDefault,@OrderValue,@DateId)";

    BLL.QuarterDateManager dllQuarterDateManager = new BLL.QuarterDateManager();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindDrp(this.drpYear);
            BindDrp(this.drpQuarterDate);
            Bind();
        }
    }

    /// <summary>
    /// 绑定图片列表
    /// </summary>
    void Bind()
    {
        int DepartmentId = HttpHelp.getParamsInt("DepartmentId");
        int typeid = HttpHelp.getParamsInt("typeid");
        SqlParameter[] parameters = new SqlParameter[2];
        parameters[0] = new SqlParameter("@DepartmentId", DepartmentId);
        parameters[1] = new SqlParameter("@DateId", Convert.ToInt32(this.drpQuarterDate.SelectedValue));
        switch (typeid)
        {
            case 1:
                this.gdvImgList.DataSource = SqlHelper.ExecuteDataset(SqlHelper.connStr,
CommandType.Text, SQL_queryIntroduction, parameters);
                break;
            case 2:
                this.gdvImgList.DataSource = SqlHelper.ExecuteDataset(SqlHelper.connStr,
CommandType.Text, SQL_queryCoreevents, parameters);
                break;
            case 3:
                this.gdvImgList.DataSource = SqlHelper.ExecuteDataset(SqlHelper.connStr,
CommandType.Text, SQL_queryManagementObject, parameters);
                break;
            case 4:
                this.gdvImgList.DataSource = SqlHelper.ExecuteDataset(SqlHelper.connStr,
CommandType.Text, SQL_queryManagementSlogans, parameters);
                break;
        }

        this.gdvImgList.DataBind();
    }


    void BindDrp(DropDownList _drp)
    {
        if (_drp.Equals(this.drpYear))
        {
            for (int i = 2009; i < 2100; i++)
            {
                ListItem li = new ListItem(i.ToString(), i.ToString());
                _drp.Items.Add(li);
            }
            //根据系统日期自动绑定当前年份
            string _year = DateTime.Now.Year.ToString();
            this.drpYear.SelectedIndex = this.drpYear.Items.IndexOf(this.drpYear.Items.FindByText(_year));
            if (Request.Params["Id"] != null && Request.Params["Id"].ToString().Length != 0)
            {
                object[] _quarterDate = new object[1];
                _quarterDate[0] = Convert.ToInt32(Request.Params["Id"].ToString());
                DataTable _quarterDateTable = dllQuarterDateManager.get(QuarterDateManager.field.Quarter_Id.ToString(), _quarterDate);
                if (_quarterDateTable.Rows.Count > 0)
                {
                    this.drpYear.SelectedIndex = this.drpYear.Items.IndexOf(this.drpYear.Items.FindByValue(_quarterDateTable.Rows[0]["QuarterYear"].ToString()));
                }
            }
        }
        if (_drp.Equals(this.drpQuarterDate))
        {
            object[] _value = new object[1];
            _value[0] = this.drpYear.SelectedValue;
            DataTable _quarter = dllQuarterDateManager.get(QuarterDateManager.field.QuarterYear.ToString(), _value);
            if (_quarter.Rows.Count != 0)
            {
                this.drpQuarterDate.DataSource = _quarter;
                this.drpQuarterDate.DataTextField = "QuarterName";
                this.drpQuarterDate.DataValueField = "Quarter_Id";
                this.drpQuarterDate.DataBind();
                #region dropdownlist显示系统所对应的当前年周期
                //根据系统当前日期查找到对应的年周期
                DataTable _quartertime = dllQuarterDateManager.getQuarterDate();
                //如果查到结果（结果只有一条）

                if (_quartertime.Rows.Count == 1)
                {
                    this.drpQuarterDate.SelectedIndex = this.drpQuarterDate.Items.IndexOf(this.drpQuarterDate.Items.FindByText(_quartertime.Rows[0][1].ToString()));
                    if (Request.Params["Id"] != null && Request.Params["Id"].ToString().Length != 0)
                    {
                        this.drpQuarterDate.SelectedIndex = this.drpQuarterDate.Items.IndexOf(this.drpQuarterDate.Items.FindByValue(Request.Params["Id"].ToString()));
                    }

                }
                #endregion

            }
            else
            {
                ListItem li = new ListItem("无年周期", "0");
                this.drpQuarterDate.Items.Clear();
                this.drpQuarterDate.Items.Add(li);
            }

        }
    }

    /// <summary>
    /// 保存
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSave_Click(object sender, EventArgs e)
    {
        int DepartmentId = HttpHelp.getParamsInt("DepartmentId");
        int typeid = HttpHelp.getParamsInt("typeid");
        List<string> listfile = new List<string>();
        if (this.fupImg.HasFiles)
        {
            foreach (var file in this.fupImg.PostedFiles)
            {
                listfile.Add(file.FileName);
            }
            listfile.Sort();
            foreach (var item in this.fupImg.PostedFiles)
            {
                //判断是否存在
                if (System.IO.File.Exists(path + item.FileName))
                {//如果存在就删除已存在
                    System.IO.File.Delete(path + item.FileName);
                }
                item.SaveAs(path + item.FileName);


                string imgUrl = "/Admin/Upload/" + item.FileName;
                string isDefault = this.drpIsDefault.SelectedValue;
                int orderValue = Convert.ToInt32(this.txtOrderValue.Text);
                int DateId = Convert.ToInt32(this.drpQuarterDate.SelectedValue);

                SqlParameter[] parameters = new SqlParameter[5];
                parameters[0] = new SqlParameter("@DepartmentId", DepartmentId);
                parameters[1] = new SqlParameter("@ImgUrl", imgUrl);
                parameters[2] = new SqlParameter("@IsDefault", isDefault);
                parameters[3] = new SqlParameter("@OrderValue", listfile.IndexOf(item.FileName) + 1);
                parameters[4] = new SqlParameter("@DateId", DateId);
                int result = 0;
                switch (typeid)
                {
                    case 1:
                        result = SqlHelper.ExecuteNonQuery(SqlHelper.connStr,
        CommandType.Text, SQL_insertIntroduction, parameters);
                        break;
                    case 2:
                        result = SqlHelper.ExecuteNonQuery(SqlHelper.connStr,
        CommandType.Text, SQL_insertCoreevents, parameters);
                        break;
                    case 3:
                        result = SqlHelper.ExecuteNonQuery(SqlHelper.connStr,
       CommandType.Text, SQL_insertManagementObject, parameters);
                        break;
                    case 4:
                        result = SqlHelper.ExecuteNonQuery(SqlHelper.connStr,
      CommandType.Text, SQL_insertManagementSlogans, parameters);
                        break;
                }
            }

            HttpHelp.alert("添加成功！", Page);
            Bind();
        }
        else
        {
            HttpHelp.alert("文件不存在，请重新选择！", Page);
        }

    }


    protected void btnDel_Click(object sender, EventArgs e)
    {
        //得到button所在行        
        Button bt = (Button)sender;//获得当前控件
        TableCell cell = (TableCell)bt.Parent;//得到所处的父单元格
        GridViewRow iRow = (GridViewRow)cell.Parent;//得到所处父单元行
        int _rowIndex = iRow.RowIndex;//得到该行的索引
        int Id = Convert.ToInt32(this.gdvImgList.DataKeys[_rowIndex]["Id"].ToString());
        string tablename = string.Empty;
        int typeid = HttpHelp.getParamsInt("typeid");
        switch (typeid)
        {
            case 1:
                tablename = "DS_IntroductionImg"; break;
            case 2:
                tablename = "DS_CoreeventsImg"; break;
            case 3:
                tablename = "DS_ManagementObject"; break;
            case 4:
                tablename = "DS_ManagementSlogans"; break;
        }
        object imgurl = null;
        string sql = "SELECT ImgUrl FROM " + tablename + " WHERE id=" + Id;
        imgurl = SqlHelper.ExecuteScalar(SqlHelper.connStr, CommandType.Text, sql);
        sql = "DELETE " + tablename + " WHERE ID=" + Id;
        int result = SqlHelper.ExecuteNonQuery(SqlHelper.connStr, CommandType.Text, sql);
        if (result > 0)
        {
            HttpHelp.alert("删除成功！", Page);
            //判断是否存在
            if (System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/") + imgurl))
            {//如果存在就删除已存在
                System.IO.File.Delete(HttpContext.Current.Server.MapPath("~/") + imgurl);
            }
            Bind();
        }
    }
    protected void btnDefault_Click(object sender, EventArgs e)
    {
        //得到button所在行        
        Button bt = (Button)sender;//获得当前控件
        TableCell cell = (TableCell)bt.Parent;//得到所处的父单元格
        GridViewRow iRow = (GridViewRow)cell.Parent;//得到所处父单元行
        int _rowIndex = iRow.RowIndex;//得到该行的索引
        int Id = Convert.ToInt32(this.gdvImgList.DataKeys[_rowIndex]["Id"].ToString());
        string tablename = string.Empty;
        int typeid = HttpHelp.getParamsInt("typeid");
        switch (typeid)
        {
            case 1:
                tablename = "DS_IntroductionImg"; break;
            case 2:
                tablename = "DS_CoreeventsImg"; break;
            case 3:
                tablename = "DS_ManagementObject"; break;
            case 4:
                tablename = "DS_ManagementSlogans"; break;
        }
        int DepartmentId = HttpHelp.getParamsInt("DepartmentId");
        string sql = "UPDATE " + tablename + " SET IsDefault=0 WHERE   DepartmentId=" + DepartmentId + " AND DateId=" + this.drpQuarterDate.SelectedValue;
        SqlHelper.ExecuteNonQuery(SqlHelper.connStr, CommandType.Text, sql);
        sql = "UPDATE " + tablename + " SET IsDefault=1 WHERE id=" + Id;
        SqlHelper.ExecuteNonQuery(SqlHelper.connStr, CommandType.Text, sql);
        HttpHelp.alert("默认成功！", Page);
        Bind();
    }
    protected void drpYear_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindDrp(this.drpQuarterDate);
        Bind();
    }
}